package git.soulbgm.controller;

import git.soulbgm.config.RsaConfig;
import git.soulbgm.utils.RsaUtils;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;

import java.security.*;
import java.util.*;
import java.security.KeyStore;

/**
 * 认证控制器
 * 处理用户登录和公钥获取等认证相关请求
 *
 * @author SoulBGM
 * @date 2025-03-03
 */
@RestController
@RequestMapping("/auth")
public class AuthController {
    private KeyPair keyPair;

    private final Resource keystoreFile;
    private final String keystorePassword;
    private final String keyAlias;
    private final String keyPassword;

    /**
     * 构造函数
     * 从密钥库文件中加载RSA密钥对
     */
    public AuthController(RsaConfig config) throws Exception {
        this.keystoreFile = config.getKeystoreFile();
        this.keystorePassword = config.getKeystorePassword();
        this.keyAlias = config.getKeyAlias();
        this.keyPassword = config.getKeyPassword();
        // 在应用启动时从密钥库加载密钥对
        loadKeyPair();
    }

    /**
     * 从密钥库加载RSA密钥对
     */
    private void loadKeyPair() throws Exception {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(keystoreFile.getInputStream(), keystorePassword.toCharArray());

        // 获取私钥
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias,
                keyPassword.toCharArray());
        // 获取公钥
        PublicKey publicKey = keyStore.getCertificate(keyAlias).getPublicKey();

        this.keyPair = new KeyPair(publicKey, privateKey);
    }

    /**
     * 获取公钥
     *
     * @return Map 包含Base64编码的公钥字符串
     */
    @GetMapping("/publicKey")
    public Map<String, String> getPublicKey() {
        String publicKey = RsaUtils.getPublicKeyString(keyPair.getPublic());
        return Collections.singletonMap("publicKey", publicKey);
    }

    /**
     * 加密文本
     *
     * @param textList 文本列表
     * @return {@link String}
     * @throws Exception 例外
     */
    @PostMapping("encrypt")
    public Map<String, String> encrypt(@RequestBody List<String> textList) throws Exception {
        Map<String, String> map = new LinkedHashMap<>(textList.size());
        for (String text : textList) {
            map.put(text, RsaUtils.encrypt(text, keyPair.getPublic()));
        }
        return map;
    }

    /**
     * 用户登录
     *
     * @param loginData 登录数据
     * @return Map 登录结果
     */
    @PostMapping("/login")
    public Map<String, String> login(@RequestBody Map<String, String> loginData) {
        try {
            // 使用私钥解密用户名和密码
            String decryptedUsername = RsaUtils.decrypt(loginData.get("username"), keyPair.getPrivate());
            String decryptedPassword = RsaUtils.decrypt(loginData.get("password"), keyPair.getPrivate());

            Map<String, String> response = new LinkedHashMap<>(3);
            response.put("message", "登录成功");
            response.put("decryptedUsername", decryptedUsername);
            response.put("decryptedPassword", decryptedPassword);
            return response;
        } catch (Exception e) {
            throw new RuntimeException("登录失败", e);
        }
    }

}